package com.exercise.ThreadLocal;

public class ThreadLocalExample {
    //创还能ThreadLocal实例
    private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            //同一个类中的代码，在类的内部，静态变量可以直接用变量名访问，不需要通过类名或对象名。
            new Thread(()->{
                //获取当前线程的threadLocal变量
                int value = threadLocal.get();
                System.out.println(Thread.currentThread().getName() + ": " + value);
                threadLocal.set(value + 1);
                System.out.println(Thread.currentThread().getName() + " after set: " + threadLocal.get());
                //清理 ThreadLocal
                threadLocal.remove();
            }).start();
        }
    }

}
